using System.IO;

namespace OpenXmlWriter.Packaging
{
  public class Relationship
  {
    private string _id;
    private string _parentPath;
    private string _targetPath;
    private string _relationshipType;
    private string _relationshipTargetPath;

    public Relationship(string parentPath, string targetPath, string relationshipType)
      : this(RelationshipHelper.GetNextId(), parentPath, targetPath, relationshipType)
    {
    }

    public Relationship(string id, string parentPath, string targetPath, string relationshipType)
    {
      _id = id;
      _parentPath = parentPath;
      _targetPath = targetPath;
      _relationshipType = relationshipType;
      _relationshipTargetPath = ResolvePath(_parentPath, _targetPath);
    }

    private static string ResolvePath(string parent, string child)
    {
      if (parent == string.Empty)
      {
        return child;
      }

      string parentPath = Path.GetDirectoryName(parent);
      string childPath = Path.GetDirectoryName(child);

      if (parentPath == childPath)
      {
        return Path.GetFileName(child);
      }

      string finalPath = childPath.Remove(0, parentPath.Length + 1);
      finalPath = Path.Combine(finalPath, Path.GetFileName(child)).Replace("\\", "/");

      return finalPath;
    }

    public string Id
    {
      get
      {
        return _id;
      }
    }

    public string ParentPath
    {
      get
      {
        return _parentPath;
      }
    }

    public string TargetPath
    {
      get
      {
        return _targetPath;
      }
    }

    public string RelationshipType
    {
      get
      {
        return _relationshipType;
      }
    }

    public string Xml
    {
      get
      {
        return
          string.Format("<Relationship Id=\"{0}\" Type=\"{1}\" Target=\"{2}\" />", _id, _relationshipType, _relationshipTargetPath);
      }
    }
  }
}